$(function () {
    $("#jqGrid").Grid({
        url: '../moldType/cost',
        rownumWidth:35,
        multiselect:false,
        jsonReader: {
            root: "statResult",
            page: "1",
            total: "statResult.length",
            records: "statResult.length"
        },
        pager: null,
        rowNum: 1000,
        colModel: [
            {label: '模具类型', name: 'moldTypeName', index: 'MODULE_TYPE', width: 80},
            {label: '单台组成数（项）', name: 'num', index: 'NUM', width: 120},
            {label: '理论单台成本', name: 'theorySingleCost', index: 'THEORY_SINGLE_COST', width: 80},
            {label: '实际单台成本', name: 'actualSingleCost', index: 'ACTUAL_SINLE_COST', width: 80},
            {label: 'moldTypeId', name: 'moldTypeId', key: true, hidden: true},
            {
                label: '备件明细', width: 80, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    // return "<button class='btn btn-outline btn-info' onclick='vm.goModuleDetail(\"" + row.id + "\", \"" + row.moduleCode + "\",\"" + row.moduleTypeName + "\")'><i class='fa fa-file-text-o'></i>&nbsp;模具详情</button>";
                    return "<button title='备件明细' class='btn btn-outline btn-info' onclick='vm.goModuleDetail(\"" + row.moldTypeId + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            }
        ]
    });
    vm.getSelect();
    vm.getTypeTree();

});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "superType",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    }
};

var moduleTypeTree;
var setting2 = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "superType",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        onClick: function () {
            var node = typeTree.getSelectedNodes();
            vm.q.moduleType = node[0].id;
            vm.query()
        }

    }
};

var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
};

var deptTree;

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        moduleArchives: {
            lifeStandard: '',
            productModel: '',
            productModelList:[],
            moduleNo: '',
            moduleType: '',
            moduleCode: '',
            id: '',
            updateDate: '',
            updateUser: '',
            createDate: '',
            createUser: '',
            delFlag: '',
            moduleModel: '',
            moduleSeries: '',
            moduleCategory: '',
            isData: '',
            firmCapitalNo: '',
            liveCode: '',
            lastCode: '',
            useNo: '',
            remainNo: '',
            currentState: '',
            startDate: '',
            subShop: '',
            moduleTypeName: '',
            buyDate:'',
            volumeProductionDate:'',
            moduleManufacturers:'',
            xiangkuaiManufacturers:'',
            xiangkuaiLifeStandard: 80000,
            xiangkuaiUseNo:0
        },
        ruleValidate: {
            moduleNo: [
                {required: true, message: '模具号必填！', trigger: 'blur'}
            ],
            moduleTypeName: [
                {required: true, message: '模具类型必选！', trigger: 'blur'}
            ]
        },
        q: {
            yearly: '',//年份
        },
        productModelList: [],
        moduleSeriesList: [],
        treeList: {},
        currentStateArray: enumsToList("MODULE_STATE"),
        moduleTypeList: enumsToListWithNull('MODULE_TYPE'),
        deptList:{},
    },
    methods: {
        goFileList: function(){
            var id = getSelectedRow("#jqGrid");
            if (!id) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 模具资料',
                content: '../sys/ermsfile.html?moduleType=2&id=' + id
            })
        },
        getSelect: function () {
            Ajax.request({
                url: "../moduleseries/queryAll",
                async: true,
                successCallback: function (res) {
                    vm.productModelList = res.list;
                }
            });
            Ajax.request({
                url: "../moduleseriestype/queryAll",
                async: true,
                successCallback: function (res) {
                    vm.moduleSeriesList = res.list;
                }
            });
            Ajax.request({
                url: "../sys/dept/getCJ",
                async: true,
                successCallback: function (res) {
                    vm.deptList = res.deptList;
                }
            });
        },
        getDeptTree: function () {
            //加载分类树
            Ajax.request({
                url: '../sys/user/treeDeptByType2/DT_ZZCJ',
                async: true,
                successCallback: function (r) {
                    deptTree = $.fn.zTree.init($("#deptTree"), deptSetting, r.list);
                    deptTree.expandAll(true);
                    var node = deptTree.getNodeByParam("deptId", vm.moduleArchives.subShop);
                    if (node) {
                        deptTree.selectNode(node);
                        vm.moduleArchives.subShop = node.deptId;
                    } else {
                        node = deptTree.getNodeByParam("deptId", "0");
                        deptTree.selectNode(node);
                    }
                }
            });
        },
        deptTreeShow: function () {
            openWindow({
                title: "选择车间",
                area: ['300px', '450px'],
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = deptTree.getSelectedNodes();
                    if (node[0] && node[0].deptType === 'DT_ZZCJ') {
                        // //选择上级菜单
                        vm.moduleArchives.subShop = node[0].deptId;
                        vm.moduleArchives.subShopName = node[0].name;
                        layer.close(index);
                    }
                }
            });
        },
        getModuleTypeTree: function () {
            //加载故障类型树
            Ajax.request({
                url: "../moduletype/select",
                async: true,
                successCallback: function (r) {
                    var tree = r.typeList;

                    moduleTypeTree = $.fn.zTree.init($("#moduleTypeTree"), setting, tree);

                    moduleTypeTree.expandAll(true);
                    var node = moduleTypeTree.getNodeByParam("id", vm.moduleArchives.moduleType);
                    if (node) {
                        moduleTypeTree.selectNode(node);
                        if (node.parentName) {
                            vm.moduleArchives.moduleTypeName = node.parentName;
                        } else {
                            vm.moduleArchives.moduleTypeName = '无';
                        }
                    } else {
                        node = moduleTypeTree.getNodeByParam("id", "0");
                        moduleTypeTree.selectNode(node);
                    }
                }
            });
        },
        typeTree: function () {
            openWindow({
                title: "选择模具类型",
                area: ['300px', '450px'],
                content: jQuery("#moduleTypeLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = moduleTypeTree.getSelectedNodes();
                    if (node.length != 0) {
                        vm.moduleArchives.moduleType = node[0].id;
                        vm.moduleArchives.moduleTypeName = node[0].typeName;
                    } else {
                        vm.moduleArchives.moduleType = 0;
                        vm.moduleArchives.moduleTypeName = '未选择';
                    }

                    layer.close(index);
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.moduleArchives = {
                lifeStandard: '',
                productModel: '',
                productModelList: [],
                moduleNo: '',
                moduleType: '',
                moduleCode: '',
                updateDate: '',
                updateUser: '',
                createDate: '',
                createUser: '',
                delFlag: 1,
                liveCode: '',
                lastCode: '',
                moduleModel: '',
                moduleSeries: '',
                moduleCategory: '',
                isData: 0,
                firmCapitalNo: '',
                useNo: '',
                remainNo: '',
                currentState: '',
                startDate: '',
                subShop: '',
                subShopName: '',
                moduleTypeName: '',
                buyDate:'',
                volumeProductionDate:'',
                moduleManufacturers:'',
                xiangkuaiManufacturers:'',
                xiangkuaiLifeStandard: 80000,
                xiangkuaiUseNo:0
            };
            vm.getModuleTypeTree();
            vm.getDeptTree();
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
            vm.getModuleTypeTree();
            vm.getDeptTree();
        },
        saveOrUpdate: function (event) {
            var url = vm.moduleArchives.id == null ? "../modulearchives/save" : "../modulearchives/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.moduleArchives),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../modulearchives/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../modulearchives/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.moduleArchives = r.moduleArchives;
                }
            });
        },
        reload: function (event) {
            let string = typeof vm.q.yearly
            if(string == 'object'){
                if ( vm.q.yearly) {
                    vm.q.yearly = gmt2YearStr(vm.q.yearly);
                }
            }
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                search: true,
                postData: {
                    'yearly': vm.q.yearly,
                },
                page: page
            }).trigger("reloadGrid", [{page:1}]);
        },
        reloadSearch: function () {
            vm.q = {
                moduleType: '',
                productModel: '',//模具机型
                moduleSeries: '',//模具系列
                currentState:'',
                moduleNo: '', // 模具号
                dept:''   ,      //所属车间
                yearly:''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        /**
         * 模具位置关联
         */
        modPosition: function () {
            var id = getSelectedRow('#jqGrid');
            if (!id) {
                return;
            }
            var result = getSelectedRowData("#jqGrid");
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 模具寿命',
                content: '../module/modulpositioncorrelation.html?moldId=' + result.id
            })
        },
        /**
         * 模具成本统计
         */
        modCostStat: function () {
            var result = getSelectedRowData("#jqGrid");
            var id = result.id;
            var moduleCode = result.moduleCode;
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 模具成本统计',
                content: '../module/moduleCostStat.html?moduleCode=' + moduleCode
            })
        },
        /**
         * 查看模具详情
         */
        goModuleDetail: function (id) {
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-bars"></i> 单台成本统计清单详情',
                content: '../module/moldUnitYearlyCostStatDetail.html?moldTypeId=' + id+'&yearly='+this.q.yearly
                //?devId='+devId+'&devCode='+devCode+ '&devName='+  encodeURI(encodeURI(devName))
            })
        },
        getTypeTree: function () {
            //加载模具类型树
            Ajax.request({
                url: "../moduletype/select",
                async: true,
                successCallback: function (r) {
                    var tree = r.typeList;
                    typeTree = $.fn.zTree.init($("#typeTree"), setting2, tree);
                    typeTree.expandAll(true);
                }
            });
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
    }
});
